package com.lanhai.crowd.util;


import com.lanhai.crowd.constant.CrowdConstant;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * 蓝海众筹网工具类
 * @author lanhai
 */
public class CrowdUtil {


    /**
     * 将明文进行md5加密并返回
     * @param source 明文来源
     * @return 密文或null
     */
    public static String md5(String source) {
        // 1.判断来源合法性
        if(isEmpty(source))
            throw new RuntimeException(CrowdConstant.MESSAGE_STRING_INVALIDATE);



        try {
            // 2.加密
            String algorithm = "md5";

            // 3.获取MessageDigest对象
            MessageDigest digest = MessageDigest.getInstance(algorithm);

            // 4.获取明文字符串的字节数组
            byte[] input = source.getBytes();

            // 5.进行加密
            byte[] output = digest.digest(input);

            // 6.创建BiggerInteger
            int signum = 1;
            BigInteger bigInteger = new BigInteger(signum, output);

            // 7. 按照16进制将bigInteger转换成字符串
            int radix = 16;
            String encoded = bigInteger.toString(radix).toUpperCase();

            // 8.返回密文
            return encoded;

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 判断请求是否为AJAX请求
     *
     * @param req
     * @return true:是AJAX请求
     * false:不是AJAX请求
     */
    public static boolean jundgeRequestType(HttpServletRequest req) {
        String accept = req.getHeader("Accept");
        String xHeader = req.getHeader("X-Requested-With");


        return (accept != null && accept.contains("application/json")) ||
                (xHeader != null && xHeader.equals("XMLHttpRequest"));
    }

    /**
     * 判断字符串是否为空
     * @param str 字符串来源
     * @return true为空
     */
    public static boolean isEmpty(String str) {
        return null == str || str.length() == 0;
    }
}
